package org.myutil;

import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;

import java.io.FileOutputStream;
import java.io.IOException;
import java.lang.reflect.Field;
import java.util.List;

/**
 * 保留数据到Excel文件
 */
public class AdvancedListToExcelExporter {

	public static <T> void exportToExcelAdvanced(List<T> dataList, Class<T> clazz, String filePath)
			throws IOException, IllegalAccessException {

		Workbook workbook = new XSSFWorkbook();
		Sheet sheet = workbook.createSheet("Data");

		Field[] fields = clazz.getDeclaredFields();

		// 创建表头
		Row headerRow = sheet.createRow(0);
		for (int i = 0; i < fields.length; i++) {
			Cell cell = headerRow.createCell(i);
			cell.setCellValue(fields[i].getName());
		}

		// 填充数据
		for (int i = 0; i < dataList.size(); i++) {
			Row row = sheet.createRow(i + 1);
			T item = dataList.get(i);

			for (int j = 0; j < fields.length; j++) {
				Field field = fields[j];
				field.setAccessible(true);

				Cell cell = row.createCell(j);
				Object value = field.get(item);

				if (value != null) {
					// 处理不同数据类型
					if (value instanceof Number) {
						cell.setCellValue(((Number) value).doubleValue());
					} else if (value instanceof Boolean) {
						cell.setCellValue((Boolean) value);
					} else if (value instanceof java.util.Date) {
						cell.setCellValue((java.util.Date) value);
					} else {
						cell.setCellValue(value.toString());
					}
				} else {
					cell.setCellValue(""); // 空值处理
				}
			}
		}

		// 自动调整列宽
		for (int i = 0; i < fields.length; i++) {
			sheet.autoSizeColumn(i);
		}

		// 写入文件
		try (FileOutputStream outputStream = new FileOutputStream(filePath)) {
			workbook.write(outputStream);
		} finally {
			workbook.close();
		}
	}
}